package org.crystalrange.softwares.web;

import java.util.List;

import org.crystalrange.softwares.model.Software;
import org.crystalrange.softwares.service.SoftwareService;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.AnnotateDataBinder;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import com.googlecode.genericdao.search.Search;

public class SoftwareSelectController extends GenericForwardComposer {

	protected SoftwareService softwareService;
	protected Software selectedSoftware;
	protected List<Software> softwares;
	protected Search searchSoftware;
	protected AnnotateDataBinder binder;

	public SoftwareService getSoftwareService() {
		return softwareService;
	}

	public void setSoftwareService(SoftwareService softwareService) {
		this.softwareService = softwareService;
	}

	public Software getSelectedSoftware() {
		return selectedSoftware;
	}

	public void setSelectedSoftware(Software selectedSoftware) {
		this.selectedSoftware = selectedSoftware;
	}

	public List<Software> getSoftwares() {
		return softwares;
	}

	public void setSoftwares(List<Software> softwares) {
		this.softwares = softwares;
	}

	@Override
	public void doAfterCompose(Component component) throws Exception {
		super.doAfterCompose(component);
		this.searchSoftware = new Search(Software.class);
		this.searchSoftware.setMaxResults(100);
		this.searchSoftware.addFetch("createdBy");
		this.softwares = this.softwareService.search(this.searchSoftware);
		component.setAttribute("controller", this);
	}

	public void onClick$buttonOk(Event event) throws Exception {
		if (this.selectedSoftware != null) {
			this.execution.setAttribute("selectedSoftware",
					this.selectedSoftware);
			this.execution.setAttribute("result", "ok");
			this.self.detach();
		} else {
			Messagebox.show("Please select a Software.");
		}
	}

	public void onClick$buttonCancel(Event event) throws Exception {
		this.execution.setAttribute("selectedSoftware", null);
		this.execution.setAttribute("result", "cancel");
		this.self.detach();
	}

	public void onClick$buttonSearch(Event event) throws Exception {
		this.execution.setAttribute("searchSoftware", this.searchSoftware);

		Window window = (Window) this.execution.createComponents(
				"~./zul/html/softwareSearch.zul", null, null);
		window.setParent(self);
		window.doModal();

		if (this.execution.getAttribute("result") == "ok") {
			this.searchSoftware = (Search) this.execution
					.getAttribute("searchSoftware");
		}

		this.softwares = this.softwareService.search(this.searchSoftware);
		this.binder.loadAll();
	}

}
